# Database utility functions
import psycopg2
import psycopg2.extras
import os
from functools import wraps

DB_CONFIG = {
    'host': os.getenv('DB_HOST', 'localhost'),
    'port': int(os.getenv('DB_PORT', 5433)),
    'database': os.getenv('DB_NAME', 'pincaicai'),
    'user': os.getenv('DB_USER', 'postgres'),
    'password': os.getenv('DB_PASSWORD', 'Yuziqian')
}

def get_db_connection():
    """Get database connection"""
    return psycopg2.connect(**DB_CONFIG)

def get_db_cursor():
    """Get database cursor"""
    conn = get_db_connection()
    return conn, conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

def execute_query(query, params=None, fetch=False, commit=False):
    """Execute database query with optional fetch and commit"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute(query, params)
        if fetch:
            result = cursor.fetchall()
            if commit:
                conn.commit()
            return result
        elif commit:
            conn.commit()
            return cursor.rowcount
        else:
            return cursor.rowcount
    except Exception as e:
        if commit:
            conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()

def log_database_operation(operation_name):
    """Decorator to log database operations"""
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                result = func(*args, **kwargs)
                return result
            except Exception as e:
                # Log error if logging is available
                try:
                    from app.utils.logging_config import app_logger
                    app_logger.log_error(
                        error_type=f"database_operation_failed",
                        error_message=str(e),
                        details={"operation": operation_name}
                    )
                except:
                    pass  # If logging fails, continue without logging
                raise e
        return wrapper
    return decorator
